import 'package:flutter/material.dart';
import '../api/auth_api.dart';

class RegisterScreen extends StatefulWidget {
  const RegisterScreen({super.key});

  @override
  _RegisterScreenState createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _emailController = TextEditingController();
  final _codeController = TextEditingController();
  final _usernameFocus = FocusNode();
  final _emailFocus = FocusNode();
  final _codeFocus = FocusNode();
  bool _isLoading = false;
  bool _isCodeSent = false;

  Future<void> _submitRegistration() async {
    if (_formKey.currentState!.validate()) {
      setState(() => _isLoading = true);
      try {
        final result = await AuthApi.registerUser(
          username: _usernameController.text,
          email: _emailController.text,
        );
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('验证码已发送: $result')),
        );
        setState(() => _isCodeSent = true);
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('注册失败: $e')),
        );
      } finally {
        setState(() => _isLoading = false);
      }
    }
  }

  Future<void> _verifyCode() async {
    if (_codeController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入验证码')),
      );
      return;
    }

    setState(() => _isLoading = true);
    try {
      final result = await AuthApi.verifyRegisterCode(
        int.parse(_codeController.text),
      );
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('注册成功: $result')),
      );
      Navigator.pop(context);
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('验证码验证失败: $e')),
      );
    } finally {
      setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('用户注册')),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(16.0),
          children: [
            TextFormField(
              controller: _usernameController,
              focusNode: _usernameFocus,
              decoration: const InputDecoration(labelText: '用户名'),
              validator: (value) => value?.isEmpty == true ? '请输入用户名' : null,
            ),
            TextFormField(
              controller: _emailController,
              focusNode: _emailFocus,
              decoration: const InputDecoration(labelText: '邮箱'),
              validator: (value) {
                if (value?.isEmpty == true) return '请输入邮箱';
                if (!RegExp(r'^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$')
                    .hasMatch(value!)) {
                  return '请输入有效的邮箱地址';
                }
                return null;
              },
            ),
            ElevatedButton(
              onPressed: _isLoading ? null : _submitRegistration,
              child: _isLoading
                  ? const CircularProgressIndicator()
                  : const Text('获取验证码'),
            ),
            if (_isCodeSent)
              TextFormField(
                controller: _codeController,
                focusNode: _codeFocus,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(labelText: '验证码'),
              ),
            if (_isCodeSent)
              ElevatedButton(
                onPressed: _isLoading ? null : _verifyCode,
                child: _isLoading
                    ? const CircularProgressIndicator()
                    : const Text('验证并注册'),
              ),
          ],
        ),
      ),
    );
  }
}
